<?php

/*
 * 支付
 */

namespace Seller\Controller;

class PayController extends BaseController {

    /**
     * 支付
     */
    public function pay() {
        if (!in_array($this->__get['type'], array('lock', 'buy', 'recharge', 'warehouse')))
            $this->error('下单类型不正确');
        if (!isset($this->__get['id']) || intval($this->__get['id']) <= 0)
            $this->error('订单标识错误');
        if (!isset($this->__get['pay_id']))
            $this->error('支付方式不正确');
        if (intval($this->__get['pay_id']) > 0) {
            $object = paymentInfo($this->__get['pay_id']); //获取支付方式
            if ($object === false)
                $this->error('支付方式不正确');
        } else if ($this->__get['pay_id'] != 'preset') {
            $this->error('支付方式不正确');
        }
        $ext = ''; //扩展消息
        switch ($this->__get['type']) {
            case 'warehouse' :
                $order_info = M('warehouse_storage_order')->where(array('id' => $this->__get['id'], 'customer_id' => $this->__seller_info['id']))->find();
                if (!$order_info)
                    $this->error('订单不存在');
                if ($this->__get['pay_id'] == 'preset') { //预付款支付
                    if ($order_info['price'] > M('customer')->where(array('id' => $this->__seller_info['id']))->getField('money')) {
                        $this->error('账户金额不足');
                    }
                    M('warehouse_storage_order')->where(array('id' => $order_info['id']))->save(array('pay_status' => 1, 'payment_type' => 'Preset', 'payment_no' => '', 'pay_time' => time()));
                    D('CustomerMoneyLog')->add(
                            array('customer_id' => $this->__seller_info['id'], 'money' => $order_info['price'], 'type' => 2, 'content' => "支付仓库保管费订单【{$order_info['sn']}】扣除【{$order_info['price']}】元", 'create_time' => time())
                    );
                    //扣除金额
                    M('customer')->where(array('id' => $this->__seller_info['id']))->setDec('money', $order_info['price']);
                    //修改库存到期日期
                    M('goods_distribution')->where(array('id' => $order_info['goods_distribution_id']))->save(array('storage_end_time' => $order_info['day_time'] . ' 00:00:00'));
                    $this->success('仓库保管费支付成功', U('Goods/distribution', array('type' => 'lock')));
                    exit;
                }
                $pay_info['pay_body'] = '仓库保管费支付';
                $pay_info['amount_total'] = $order_info['price'];
                $pay_info['ref'] = $order_info['sn'];
                $pay_type = 'warehouse';
                break;
            case 'lock' : //锁货下单支付
                $order_info = M('order_goods_distribution_lock')->where(array('sn' => $this->__get['id']))->find();
                if (!$order_info)
                    $this->error('订单不存在');
                if ($order_info['status'] == 1)
                    $this->error('订单已支付，请勿重复请求');
                //检测库存是否足够
                if ($order_info['stock_num'] > M('goods_supply')->where(array('id' => $order_info['goods_supply_id']))->getField('stock_num')) {
                    $this->error('非常抱歉，库存不足不能支付');
                }
                if ($this->__get['pay_id'] == 'preset') { //预付款支付
                    if ($order_info['pay_total_price'] > M('customer')->where(array('id' => $this->__seller_info['id']))->getField('money')) {
                        $this->error('账户金额不足');
                    }
                    //修改锁货订单状态
                    M('order_goods_distribution_lock')->where(array('sn' => $order_info['sn']))->save(array('status' => 1, 'payment_type' => 'Preset', 'payment_no' => '', 'pay_time' => date('Y-m-d H:i:s')));
                    //修改供应商产品库存
                    M('goods_supply')->where(array('id' => $order_info['goods_supply_id']))->setDec('stock_num', $order_info['stock_num']);
                    $orgin_data = unserialize($order_info['orgin_data']);
                    //判断是增加还是新入库
                    if ($goods_supply = M('goods_distribution')->where(array('goods_supply_id' => $orgin_data['goods_supply_id'], 'customer_id' => $orgin_data['customer_id']))->find()) {
                        //增加锁定库存
                        if (!M('goods_distribution')->where(array('id' => $goods_supply['id']))->save(array('stock_num' => $goods_supply['stock_num'] + $orgin_data['stock_num']))) {
                            $this->error('入库失败');
                        }
                    } else {
                        //支付单入库
                        if (M('goods_distribution')->create($orgin_data) === false) {
                            $this->error('分销订单支付失败');
                        }
                        if (M('goods_distribution')->add() === false) {
                            $this->error('分销订单支付失败');
                        }
                    }
                    //更新热度值
                    hotSortNumSave($orgin_data['goods_id']);
                    D('CustomerMoneyLog')->add(
                            array('customer_id' => $this->__seller_info['id'], 'money' => $order_info['pay_total_price'], 'type' => 2, 'content' => "锁货订单【{$order_info['sn']}】扣除【{$order_info['pay_total_price']}】元", 'create_time' => time())
                    );
                    //扣除金额
                    M('customer')->where(array('id' => $this->__seller_info['id']))->setDec('money', $order_info['pay_total_price']);
                    $this->success('分销订单支付成功', U('Goods/distribution', array('type' => 'lock')));
                    exit;
                } else {
                    $pay_info['pay_body'] = '锁货下单';
                    $pay_info['amount_total'] = $order_info['pay_total_price'];
                    $pay_info['ref'] = $order_info['sn'];
                    $pay_type = 'lock';
                }
                break;
            case 'buy' : //购买
                $order_line_model = M('order_line');
                //获得支付订单状态
                $order_refs = $order_line_model->where(array('id' => $this->__get['id']))->getField('ref');
                $order_info = $order_line_model->alias('ol')->join('__ORDER__ o ON o.id = ol.order_id')->field('ol.*')->where(array('o.distribution_customer_id' => $this->__seller_info['id'], 'ol.ref' => $order_refs))->select();
                //判断订单是否存在
                if (!$order_info)
                    $this->error('支付订单信息不存在');
                //判断订单是否已经支付
                $status_flat = true;
                foreach ($order_info as $key => $val) {
                    $val['pay_status'] == 1 || $val['pay_status'] == 0 ? $status_flat = false : '';
                }
                if ($status_flat === true)
                    tipsDivError('订单已支付请勿重复支付');

                //获得本次应该支付的金额
                $pay_money = 0;
                foreach ($order_info as $key => $value) {
                    if ($value['pay_status'] < 2) {
                        $surely_total = order_status_surely_pay_price($value['id']);
                        $pay_money += $surely_total[0];
                    }
                }
                if ($this->__get['pay_id'] == 'preset') { //预付款支付
                    if ($pay_money > M('customer')->where(array('id' => $this->__seller_info['id']))->getField('money')) {
                        $this->error('账户金额不足');
                    }
                    $order_line_model->where(array('supply_customer_id' => $order_info['supply_customer_id'], 'ref' => $order_info['ref']))->save(array('pay_time' => time(), 'pay_status' => 1, 'pay_money' => $pay_money, 'pay_type' => 'Preset', 'payment_no' => '', 'payment_id' => 0));
                    //获得支付状态值
                    $pay_status = 2;
                    $order_line_payment = $order_line_model->where(array('ref' => $order_info['ref']))->field('pay_status')->select();
                    foreach ($order_line_payment as $key => $value) {
                        if (!$value['pay_status'])
                            $pay_status = 1;
                    }
                    //订单支付状态
                    M('order')->where(array('ref' => $order_info['ref']))->save(array('pay_status' => $pay_status));
                    D('CustomerMoneyLog')->add(
                            array('customer_id' => $this->__seller_info['id'], 'money' => $pay_money, 'type' => 2, 'content' => "订单【{$order_info['ref']}】扣除【{$pay_money}】元", 'create_time' => time())
                    );
                    //扣除金额
                    D('customer')->where(array('id' => $this->__seller_info['id']))->setDec('money', $pay_money);
                    $this->success('支付成功', U('Order/distributionList'));
                    exit;
                } else {
                    $ext = '_' . $surely_total[1];
                    $pay_info['pay_body'] = '订单：' . $order_info[0]['ref'] . '支付';
                    $pay_info['amount_total'] = $pay_money;
                    $pay_info['ref'] = $order_info[0]['ref'] . '_' . $order_info[0]['supply_customer_id'] . $ext;
                    $pay_type = 'buy';
                }
                break;
            case 'recharge' : //充值
                //验证金额是否正确
                if (!isset($this->__get['price']) || !preg_match('/^[0-9]+(\.[0-9]+)?$/is', $this->__get['price']))
                    $this->error('订单标识错误');
                //充值订单信息添加入库
                $add_data = array(
                    'sn' => time() . rand(10000, 99999),
                    'customer_id' => $this->__seller_info['id'],
                    'price' => $this->__get['price'],
                    'create_time' => time()
                );
                M('order_recharge')->add($add_data);
                $pay_type = 'recharge';
                $pay_info['pay_body'] = "给钱包充值【{$add_data['price']}】元";
                $pay_info['amount_total'] = $add_data['price'];
                $pay_info['ref'] = $add_data['sn'];
                break;
        }
        $pay_info['notify_url'] = 'http://' . $_SERVER['SERVER_NAME'] . '/seller.php?m=Seller&c=Pay&a=notify&pay_type=' . $pay_type . '&type=' . $object['object_name'] . '&pay_id=' . $this->__get['pay_id'];
        $object['object']->pay($pay_info);
    }

    /**
     * 支付回调
     */
    public function notify() {
        if (!in_array($this->__get['pay_type'], array('lock', 'buy', 'recharge', 'warehouse'))) {
            exit();
        }
        if (!in_array($this->__get['type'], array('Alipay', 'Weixin'))) {
            exit();
        }
        if (isset($this->__get['pay_id']) && intval($this->__get['pay_id']) > 0) {
            $payInfo = M('payment_config')->where(array('id' => $this->__get['pay_id']))->find();
            if (!$payInfo) {
                $this->error('支付不存在！');
                die;
            }
            $object_name = '\\Api\\Extend\\Payment\\' . ucfirst($this->__get['type']); //组合空间命名
            $info = unserialize($payInfo['info']);
            $object = new $object_name($info);
            $pay_type = $this->__get['pay_type'];
            $pay_id = $this->__get['pay_id'];
            $type = $this->__get['type'];
            unset($this->__get['type']);
            unset($this->__get['pay_id']);
            unset($this->__get['m']);
            unset($this->__get['c']);
            unset($this->__get['a']);
            unset($this->__get['pay_type']);
            $rsult = $object->notify($this->__get);
            if ($rsult['status'] == 'success') {
                switch ($pay_type) {
                    case 'warehouse' :
                        $order_info = M('warehouse_storage_order')->where(array('sn' => $rsult['order_sn'], 'customer_id' => $this->__seller_info['id']))->find();
                        if (!$order_info)
                            $this->error('订单不存在');
                        //支付金额认证
                        if ($order_info['price'] != $rsult['total_fee']) {
                            $this->error('支付金额和订单金额不匹配');
                        }
                        M('warehouse_storage_order')->where(array('id' => $order_info['id']))->save(array('pay_status' => 1, 'payment_type' => $type, 'payment_no' => $rsult['payment_no'], 'pay_money' => $rsult['total_fee'], 'pay_time' => time()));
                        D('CustomerMoneyLog')->add(
                                array('customer_id' => $this->__seller_info['id'], 'money' => $rsult['total_fee'], 'type' => 1, 'content' => "充值【{$rsult['total_fee']}】元，流水号：{$rsult['payment_no']}", 'create_time' => time())
                        );
                        D('CustomerMoneyLog')->add(
                                array('customer_id' => $this->__seller_info['id'], 'money' => $order_info['price'], 'type' => 2, 'content' => "支付仓库保管费订单【{$order_info['sn']}】扣除【{$order_info['price']}】元", 'create_time' => time())
                        );
                        //修改库存到期日期
                        M('goods_distribution')->where(array('id' => $order_info['goods_distribution_id']))->save(array('storage_end_time' => $order_info['day_time'] . ' 00:00:00'));
                        $this->success('仓库保管费支付成功', U('Goods/distribution', array('type' => 'lock')));
                        exit;
                        break;
                    case 'buy' : //分销平台购买下单
                        $ref = explode('_', $rsult['order_sn']);
                        $order_line_model = M('order_line');
                        //获得支付订单状态
                        $order_info = $order_line_model->alias('ol')->join('__ORDER__ o ON o.id = ol.order_id')
                                        ->where(array('o.distribution_customer_id' => $this->__seller_info['id'], 'ol.ref' => $ref[0], 'ol.supply_customer_id' => $ref[1]))->field('ol.*')->select();
                        //判断订单是否存在
                        if (!$order_info)
                            $this->error('支付订单信息不存在');
                        //判断订单是否已经支付
                        if ($order_info[0]['pay_status'] == 2)
                            $this->error('订单已支付请勿重复支付');
                        //获得本次应该支付的金额
                        $pay_money = 0;
                        foreach ($order_info as $key => $value) {
                            $surely_total = order_status_surely_pay_price($value['id']);
                            $pay_money += $surely_total[0];
                        }
                        //验证支付金额
                        if ($pay_money != $rsult['total_fee'])
                            $this->error('支付金额和订单金额不匹配');

                        //修改支付清单支付信息
                        foreach ($order_info as $key => $value) {
                            M('order_line_pay')->where(array('order_line_id' => $value['id'], 'step' => $ref[2]))->save(array('pay_time' => time(), 'pay_status' => 1, 'pay_type' => $type, 'payment_no' => $rsult['payment_no'], 'payment_id' => $pay_id));
                        }

                        //根据不同的支付步骤来做不同的操作
                        switch ($ref[2]) {
                            case '1' :
                                //验证是否已经没有下步支付了
                                $order_line_data = $order_line_model->where(array('ref' => $ref[0]))->select();
                                foreach ($order_line_data as $key => $value) {
                                    //如果没有下步支付直接修改为已全部支付
                                    if (M('order_line_pay')->where(array('order_line_id' => $value['id'], 'pay_status' => '0'))->count() <= 0) {
                                        $order_line_model->save(array('pay_status' => 2, 'status' => 1, 'id' => $value['id']));
                                    } else {
                                        $order_line_model->save(array('pay_status' => 1, 'status' => 1, 'id' => $value['id']));
                                    }
                                }
                                $pay_status = 1;
                                break;
                            case '2' :
                                //更改状态
                                $order_line_model->where(array('ref' => $ref[0]))->save(array('pay_status' => 2, 'status' => 3));
                                $pay_status = 2;
                                break;
                        }

                        //订单支付状态
                        M('order')->where(array('ref' => $ref[0]))->save(array('pay_status' => $pay_status));
                        //增加日志数据
                        D('CustomerMoneyLog')->add(
                                array('customer_id' => $this->__seller_info['id'], 'money' => $rsult['total_fee'], 'type' => 1, 'content' => "充值【{$rsult['total_fee']}】元，流水号：{$rsult['payment_no']}", 'create_time' => time())
                        );
                        D('CustomerMoneyLog')->add(
                                array('customer_id' => $this->__seller_info['id'], 'money' => $rsult['total_fee'], 'type' => 2, 'content' => "订单【{$order_info['ref']}】扣除【{$rsult['total_fee']}】元", 'create_time' => time())
                        );
                        $this->success('支付成功', U('Order/distributionList'));
                        break;
                    case 'recharge' : //本地账户充值
                        $order_info = M('order_recharge')->where(array('sn' => $rsult['order_sn']))->find();
                        //验证合法
                        if (!$order_info || $order_info['customer_id'] != $this->__seller_info['id'] || $order_info['price'] != $rsult['total_fee'])
                            $this->error('订单异常！');
                        //修改订单数据
                        M('order_recharge')->where(array('sn' => $rsult['order_sn']))->save(array('pay_status' => 1, 'payment_time' => time(), 'payment_type' => $type, 'payment_no' => $rsult['payment_no']));
                        //增加日志数据
                        D('CustomerMoneyLog')->add(
                                array('customer_id' => $this->__seller_info['id'], 'money' => $rsult['total_fee'], 'type' => 1, 'content' => "充值【{$rsult['total_fee']}】元，流水号：{$rsult['payment_no']}", 'create_time' => time())
                        );
                        //增加本地钱包金额
                        M('customer')->where(array('id' => $this->__seller_info['id']))->setInc('money', $rsult['total_fee']);
                        $this->success('充值成功', U('Accunt/local'));
                        break;
                    case 'lock' : //分销锁货
                        //更改分销锁货订单支付状态
                        $order_info = M('order_goods_distribution_lock')->where(array('sn' => $rsult['order_sn']))->find();
                        if (!$order_info) {
                            $this->error('订单不存在！');
                        }
                        if ($order_info['status'] != 0) {
                            $this->error('订单已支付，请勿重复支付', U('Goods/distribution'));
                        }
                        //验证支付金额
                        if ($order_info['pay_total_price'] != $rsult['total_fee'])
                            $this->error('支付金额和订单金额不匹配');
                        //修改锁货订单状态
                        M('order_goods_distribution_lock')->where(array('sn' => $rsult['order_sn']))->save(array('status' => 1, 'payment_type' => $type, 'payment_no' => $rsult['payment_no'], 'pay_time' => date('Y-m-d H:i:s')));
                        //修改供应商产品库存
                        M('goods_supply')->where(array('id' => $order_info['goods_supply_id']))->setDec('stock_num', $order_info['stock_num']);
                        $orgin_data = unserialize($order_info['orgin_data']);
                        //判断是增加还是新入库
                        if ($goods_supply = M('goods_distribution')->where(array('goods_supply_id' => $orgin_data['goods_supply_id'], 'customer_id' => $orgin_data['customer_id']))->find()) {
                            //增加锁定库存
                            if (!M('goods_distribution')->where(array('id' => $goods_supply['id']))->save(array('stock_num' => $goods_supply['stock_num'] + $orgin_data['stock_num']))) {
                                $this->error('入库失败');
                            }
                        } else {
                            //支付单入库
                            if (M('goods_distribution')->create($orgin_data) === false) {
                                $this->error('分销订单支付失败');
                            }
                            if (M('goods_distribution')->add() === false) {
                                $this->error('分销订单支付失败');
                            }
                        }
                        //更新热度值
                        hotSortNumSave($orgin_data['goods_id']);
                        //更新统计数据
                        goods_supply_count_save($order_info['goods_supply_id'], 'total_lock_sale', $order_info['stock_num']); //锁货总库存
                        goods_supply_count_save($order_info['goods_supply_id'], 'total_lock_sale_price', $order_info['total_price']); //锁货总金额
                        goods_supply_count_save($order_info['goods_supply_id'], 'residue_lock_stock', $order_info['stock_num']); //剩余锁货库存
                        goods_supply_count_save($order_info['goods_supply_id'], 'use_total_stock', $order_info['stock_num'], 2); //总共可用库存
                        //增加日志数据
                        D('CustomerMoneyLog')->add(
                                array('customer_id' => $this->__seller_info['id'], 'money' => $rsult['total_fee'], 'type' => 1, 'content' => "充值【{$rsult['total_fee']}】元，流水号：{$rsult['payment_no']}", 'create_time' => time())
                        );
                        D('CustomerMoneyLog')->add(
                                array('customer_id' => $this->__seller_info['id'], 'money' => $rsult['total_fee'], 'type' => 2, 'content' => "锁货订单【{$order_info['sn']}】扣除【{$rsult['total_fee']}】元", 'create_time' => time())
                        );
                        $this->success('分销订单支付成功', U('Goods/distribution'));
                        break;
                }
                exit;
            }
        }
        $this->error('未知错误！');
        die;
    }

}
